package com.example.service.impl;

import com.example.config.RabbitMqConfig;
import com.example.service.ProducerService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author : fujc-dev@qq.com
 * @created : 2022/10/11 14:12
 */

@Service
public class ProducerServiceImpl implements ProducerService {

    private static final Logger LOG = LogManager.getLogger();

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送json格式数据
     *
     * @param o
     */
    @Override
    public void sendTestJson(Object o) {

        rabbitTemplate.convertAndSend(RabbitMqConfig.DIRECT_EXCHANGE, RabbitMqConfig.DIRECT_ROUTING_KEY, o);
        LOG.info("json格式的数据发送成功 发送时间为" + formatter.format(new Date()));
    }

    /**
     * 延时发送map格式数据
     *
     * @param map
     */
    @Override
    public void sendDelayTestMap(Map map) {
        rabbitTemplate.convertAndSend(RabbitMqConfig.DELAY_EXCHANGE, RabbitMqConfig.DELAY_ROUTING_KEY, map, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {

                message.getMessageProperties().setHeader("x-delay", 5000);

                return message;
            }
        });
        LOG.info("map格式的数据发送成功 发送时间为" + formatter.format(new Date()));
    }
}